package com.anjingsi.tools.file;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

import static org.apache.commons.codec.binary.Base64.encodeBase64;

/**
 * @program: jaas-cloud-isj
 * @description
 * @author: 安静思
 * @create: 2019-07-22 16:23
 **/
public class ImgBase64Utils {

    public static String imgBase64(MultipartFile multipartFile, String path){
        String imgBase64 = "";
        try {
            String fileName = UUID.randomUUID().toString()+ multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            File file = MultipartFileUtils.multipartFileToFile(multipartFile,path,fileName);
            byte[] content = new byte[(int) file.length()];
            FileInputStream finputstream = new FileInputStream(file);
            finputstream.read(content);
            finputstream.close();
            imgBase64 = new String(encodeBase64(content));
            file.delete();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return imgBase64;
    }

}
